<?php
declare(strict_types=1);

namespace app\controller\user;

use app\controller\BaseController;
use app\model\{MemberPackage, UserPackage, UserPaymentRecord};
use app\service\PaymentService;
use think\exception\ValidateException;
use think\facade\{Cache, Db};

class UserPackageController extends BaseController
{
    /**
     * 获取会员套餐列表
     * @return \think\response\Json
     */
    public function packages()
    {
        $merchant = $this->request->merchant;
        
        // 从缓存获取套餐列表
        $cacheKey = "member_packages_{$merchant->id}";
        $list = Cache::get($cacheKey);
        
        if (!$list) {
            $list = MemberPackage::where([
                    'merchant_id' => $merchant->id,
                    'status' => 1
                ])
                ->field([
                    'id', 'package_name', 'package_price', 'package_desc',
                    'discount_rate', 'valid_time'
                ])
                ->order('package_price', 'asc')
                ->select()
                ->toArray();

            // 缓存5分钟
            Cache::set($cacheKey, $list, 300);
        }

        return $this->success([
            'list' => $list
        ]);
    }

    /**
     * 购买会员套餐
     * @return \think\response\Json
     */
    public function buy()
    {
        $params = $this->request->post();
        $user = $this->request->user;
        $merchant = $this->request->merchant;

        try {
            validate([
                'package_id' => 'require|number',
                'payment_method' => 'require|in:balance,wechat,alipay'
            ], [
                'package_id.require' => '请选择套餐',
                'package_id.number' => '套餐ID必须为数字',
                'payment_method.require' => '请选择支付方式',
                'payment_method.in' => '支付方式不正确'
            ])->check($params);

            // 获取套餐信息
            $package = MemberPackage::where([
                'id' => $params['package_id'],
                'merchant_id' => $merchant->id,
                'status' => 1
            ])->find();

            if (!$package) {
                return $this->error('套餐不存在或已下架');
            }

            // 开启事务
            Db::startTrans();
            try {
                if ($params['payment_method'] == 'balance') {
                    // 余额支付
                    if ($user->balance < $package->package_price) {
                        throw new \Exception('余额不足');
                    }

                    // 扣除余额
                    $user->save([
                        'balance' => Db::raw("balance-{$package->package_price}")
                    ]);

                    // 记录余额流水
                    UserBalanceFlow::create([
                        'merchant_id' => $merchant->id,
                        'user_id' => $user->id,
                        'type' => 6, // 购买会员
                        'balance_change' => -$package->package_price,
                        'balance_before' => $user->balance,
                        'balance_after' => $user->balance - $package->package_price
                    ]);

                    // 创建会员记录
                    $userPackage = $this->createUserPackage($user, $merchant, $package);

                    Db::commit();
                    return $this->success([
                        'package_id' => $userPackage->id,
                        'payment_status' => 'success'
                    ]);

                } else {
                    // 在线支付
                    // 创建支付记录
                    $payment = UserPaymentRecord::create([
                        'merchant_id' => $merchant->id,
                        'user_id' => $user->id,
                        'business_type' => 3, // 会员购买
                        'payment_amount' => $package->package_price,
                        'payment_method' => $params['payment_method'],
                        'payment_status' => 0 // 未支付
                    ]);

                    // 调用支付服务获取支付参数
                    $payService = new PaymentService($merchant);
                    $payParams = $payService->createPayment($payment, $params['payment_method']);

                    Db::commit();
                    return $this->success([
                        'payment_id' => $payment->id,
                        'payment_status' => 'pending',
                        'payment_params' => $payParams
                    ]);
                }

            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }

        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 我的会员信息
     * @return \think\response\Json
     */
    public function info()
    {
        $user = $this->request->user;

        $package = UserPackage::where('user_id', $user->id)
            ->where('valid_time', '>', time())
            ->order('id', 'desc')
            ->find();

        return $this->success([
            'package' => $package
        ]);
    }

    /**
     * 创建用户会员记录
     */
    protected function createUserPackage($user, $merchant, $package): UserPackage
    {
        return UserPackage::create([
            'merchant_id' => $merchant->id,
            'user_id' => $user->id,
            'package_id' => $package->id,
            'package_name' => $package->package_name,
            'package_price' => $package->package_price,
            'package_desc' => $package->package_desc,
            'discount_rate' => $package->discount_rate,
            'valid_time' => time() + ($package->valid_time * 86400) // 有效期(天)转为秒
        ]);
    }
} 